// 注入脚本 - 拦截网络请求并实时通信
(function() {
  'use strict';

  // 保存原始方法
  const originalFetch = window.fetch;
  const originalXMLHttpRequest = window.XMLHttpRequest;
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;

  // 拦截配置
  let interceptConfig = {
    enabled: true,
    intercepted: []
  };

  // 监听来自content script的配置更新
  window.addEventListener('message', function(event) {
    if (event.source !== window) return;

    if (event.data.type === 'UPDATE_INTERCEPT_DATA') {
      interceptConfig = event.data.data;
      console.log('🔧 拦截配置已更新:', {
        enabled: interceptConfig.enabled,
        batchDisableEnabled: interceptConfig.batchDisableEnabled,
        interceptedCount: interceptConfig.intercepted ? interceptConfig.intercepted.length : 0,
        interceptedItems: interceptConfig.intercepted
      });

      // 立即测试配置是否正确
      if (interceptConfig.intercepted && interceptConfig.intercepted.length > 0) {
        console.log('✅ 拦截规则已加载，共', interceptConfig.intercepted.length, '条规则');
        interceptConfig.intercepted.forEach((item, index) => {
          console.log(`  规则 ${index + 1}: ${item.url} (${item.enabled ? '启用' : '禁用'})`);
        });
      } else {
        console.log('⚠️ 没有拦截规则或规则为空');
      }
    }
  });

  // 拦截fetch API
  window.fetch = function(input, init = {}) {
    const url = typeof input === 'string' ? input : input.url;
    const method = init?.method || 'GET';

    // 检查是否有拦截规则需要修改请求头
    const normalizedRequestUrl = normalizeUrl(url);
    const interceptedItem = interceptConfig.enabled && !interceptConfig.batchDisableEnabled && interceptConfig.intercepted.find(item => {
      if (!item.enabled) return false;
      const normalizedInterceptUrl = normalizeUrl(item.url);
      return normalizedInterceptUrl === normalizedRequestUrl;
    });

    // 如果有拦截规则，应用修改的请求头
    if (interceptedItem) {
      console.log('🔍 找到拦截规则:', interceptedItem);
      console.log('🔍 拦截规则的editedParams:', interceptedItem.editedParams);

      if (interceptedItem.editedParams && interceptedItem.editedParams.requestHeaders) {
        console.log('🔧 应用拦截的请求头:', interceptedItem.editedParams.requestHeaders);

        // 直接替换请求头，不合并
        console.log('🔍 原始请求头:', init?.headers);

        try {
          const interceptHeaders = typeof interceptedItem.editedParams.requestHeaders === 'string'
            ? JSON.parse(interceptedItem.editedParams.requestHeaders)
            : interceptedItem.editedParams.requestHeaders;

          console.log('🔍 解析后的拦截请求头:', interceptHeaders);

          // 直接使用拦截的请求头，完全替换原始请求头
          init = {
            ...init,
            headers: interceptHeaders
          };

          console.log('✅ Fetch请求头已完全替换:', interceptHeaders);
        } catch (error) {
          console.error('❌ 解析拦截请求头失败:', error);
        }
      } else {
        console.log('⚠️ 拦截规则中没有requestHeaders数据');
      }
    }

    // 收集请求信息 - 原封不动地捕获请求头
    let actualRequestHeaders = {};

    // 如果headers是Headers对象，转换为普通对象，保持原始大小写
    if (init?.headers) {
      if (init.headers instanceof Headers) {
        // Headers对象转换，保持原始键名
        for (let [key, value] of init.headers.entries()) {
          actualRequestHeaders[key] = value;
        }
      } else if (Array.isArray(init.headers)) {
        // 数组格式 [['key', 'value'], ...]
        init.headers.forEach(([key, value]) => {
          actualRequestHeaders[key] = value;
        });
      } else if (typeof init.headers === 'object') {
        // 普通对象直接复制，保持原始键名
        actualRequestHeaders = { ...init.headers };
      }
    }

    console.log('🔍 原始捕获的请求头:', actualRequestHeaders);

    // 尝试获取更完整的请求头信息
    // 注意：这里我们只能获取到JavaScript中设置的请求头
    // 浏览器自动添加的请求头（如Accept、User-Agent等）无法通过JavaScript获取
    // 但我们可以在编辑器中提供常见请求头的模板供用户参考

    const requestInfo = {
      url: url,
      method: method,
      timestamp: Date.now(),
      requestHeaders: actualRequestHeaders,
      requestBody: init?.body || null,
      // 添加一个标记，表示这些是捕获到的请求头，可能不完整
      _headersCaptured: Object.keys(actualRequestHeaders).length > 0
    };

    // 调用原始fetch（使用可能修改过的init）
    return originalFetch.call(this, input, init).then(response => {
      // 检查是否有拦截的响应数据（只拦截启用的规则）
      console.log('🔍 检查拦截匹配 - 请求URL:', url);
      console.log('🔍 当前拦截配置:', interceptConfig);

      // 规范化请求URL
      const normalizedRequestUrl = normalizeUrl(url);
      console.log('🔍 规范化请求URL:', normalizedRequestUrl);

      const interceptedItem = interceptConfig.enabled && !interceptConfig.batchDisableEnabled && interceptConfig.intercepted.find(item => {
        if (!item.enabled) {
          console.log('❌ 拦截规则已禁用:', item.url);
          return false;
        }

        // 规范化拦截URL
        const normalizedInterceptUrl = normalizeUrl(item.url);
        const match = normalizedInterceptUrl === normalizedRequestUrl;

        console.log('🔍 比较URL:', {
          originalRequestUrl: url,
          originalInterceptUrl: item.url,
          normalizedRequestUrl: normalizedRequestUrl,
          normalizedInterceptUrl: normalizedInterceptUrl,
          match: match,
          itemEnabled: item.enabled,
          hasResponseData: !!item.responseData,
          requestUrlLength: normalizedRequestUrl.length,
          interceptUrlLength: normalizedInterceptUrl.length,
          charByCharMatch: match ? [] : normalizedRequestUrl.split('').map((char, i) => ({
            index: i,
            requestChar: char,
            interceptChar: normalizedInterceptUrl[i],
            match: char === normalizedInterceptUrl[i],
            requestCharCode: char.charCodeAt(0),
            interceptCharCode: normalizedInterceptUrl[i] ? normalizedInterceptUrl[i].charCodeAt(0) : 'undefined'
          })).filter(c => !c.match).slice(0, 5) // 只显示前5个不匹配的字符
        });

        // 完全匹配：规范化后的拦截地址和请求地址必须完全一样才拦截
        return match;
      });

      console.log('🔍 拦截查找结果:', {
        found: !!interceptedItem,
        hasResponseData: interceptedItem ? !!interceptedItem.responseData : false,
        interceptedItem: interceptedItem
      });

      if (interceptedItem && interceptedItem.responseData) {
        console.log('🎯 拦截Fetch响应:', url);

        // 通知content script有新请求（被拦截）
        window.postMessage({
          type: 'NEW_REQUEST',
          request: {
            ...requestInfo,
            responseData: interceptedItem.responseData,
            responseHeaders: Object.fromEntries(response.headers.entries()),
            intercepted: true
          }
        }, '*');

        // 返回拦截的数据，但保持原始响应的结构
        return new Response(interceptedItem.responseData, {
          status: response.status,
          statusText: response.statusText,
          headers: response.headers
        });
      }

      // 克隆响应以便读取数据
      const clonedResponse = response.clone();
      clonedResponse.text().then(responseData => {
        // 通知content script有新请求和响应
        window.postMessage({
          type: 'NEW_REQUEST',
          request: {
            ...requestInfo,
            responseData: responseData,
            responseHeaders: Object.fromEntries(response.headers.entries())
          }
        }, '*');
      }).catch(() => {
        // 如果读取响应失败，只发送请求信息
        window.postMessage({
          type: 'NEW_REQUEST',
          request: requestInfo
        }, '*');
      });

      return response;
    });
  };

  // 拦截XMLHttpRequest
  XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    this._interceptorData = {
      url,
      method,
      requestHeaders: {},
      timestamp: Date.now()
    };

    // 检查是否有拦截规则需要修改请求头
    const normalizedRequestUrl = normalizeUrl(url);
    const interceptedItem = interceptConfig.enabled && !interceptConfig.batchDisableEnabled && interceptConfig.intercepted.find(item => {
      if (!item.enabled) return false;
      const normalizedInterceptUrl = normalizeUrl(item.url);
      return normalizedInterceptUrl === normalizedRequestUrl;
    });

    // 保存拦截信息，在send时应用
    this._interceptedItem = interceptedItem;

    return originalOpen.call(this, method, url, async, user, password);
  };

  // 拦截setRequestHeader来收集请求头
  const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
  XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
    if (this._interceptorData) {
      // 保存原始请求头用于显示
      this._interceptorData.requestHeaders[name] = value;
      console.log(`🔍 XHR捕获请求头: ${name} = ${value}`);
    }

    // 如果有拦截规则，记录但不设置原始请求头
    if (this._interceptedItem && this._interceptedItem.editedParams && this._interceptedItem.editedParams.requestHeaders) {
      console.log(`🚫 XHR拦截模式，不设置原始请求头: ${name} = ${value}`);
      // 标记这个XHR已经被拦截，在send时只设置拦截的请求头
      this._isIntercepted = true;
      return; // 不设置原始请求头
    }

    // 只有在没有拦截规则时才设置原始请求头
    return originalSetRequestHeader.call(this, name, value);
  };

  XMLHttpRequest.prototype.send = function(data) {
    const xhr = this;

    // 保存请求体数据
    if (xhr._interceptorData && data) {
      xhr._interceptorData.requestBody = data;
    }

    // 如果是拦截模式，只设置拦截的请求头
    if (xhr._isIntercepted && xhr._interceptedItem && xhr._interceptedItem.editedParams && xhr._interceptedItem.editedParams.requestHeaders) {
      console.log('🔧 XHR拦截模式：只设置拦截的请求头');

      try {
        const interceptHeaders = typeof xhr._interceptedItem.editedParams.requestHeaders === 'string'
          ? JSON.parse(xhr._interceptedItem.editedParams.requestHeaders)
          : xhr._interceptedItem.editedParams.requestHeaders;

        // 只设置拦截规则中的请求头
        Object.entries(interceptHeaders).forEach(([name, value]) => {
          originalSetRequestHeader.call(xhr, name, value);
          console.log(`✅ XHR设置拦截请求头: ${name} = ${value}`);
        });

      } catch (error) {
        console.error('❌ XHR处理拦截请求头失败:', error);
      }
    }

    // 保存原始的事件处理器
    const originalOnReadyStateChange = xhr.onreadystatechange;
    const originalOnLoad = xhr.onload;

    // 重写事件处理器来收集响应数据和处理拦截
    let responseSent = false;

    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr._interceptorData && !responseSent) {
        responseSent = true;

        // 收集响应头
        const responseHeaders = {};
        try {
          const headerString = xhr.getAllResponseHeaders();
          if (headerString) {
            headerString.split('\r\n').forEach(line => {
              const parts = line.split(': ');
              if (parts.length === 2) {
                responseHeaders[parts[0]] = parts[1];
              }
            });
          }
        } catch (e) {
          console.warn('Failed to get response headers:', e);
        }

        // 检查是否有拦截的响应数据
        const requestUrl = xhr._interceptorData.url;
        console.log('🔍 XHR检查拦截匹配 - 请求URL:', requestUrl);

        // 规范化请求URL
        const normalizedRequestUrl = normalizeUrl(requestUrl);
        console.log('🔍 XHR规范化请求URL:', normalizedRequestUrl);

        const interceptedItem = interceptConfig.enabled && !interceptConfig.batchDisableEnabled &&
          interceptConfig.intercepted.find(item => {
            if (!item.enabled) {
              console.log('❌ XHR拦截规则已禁用:', item.url);
              return false;
            }

            // 规范化拦截URL
            const normalizedInterceptUrl = normalizeUrl(item.url);
            const match = normalizedInterceptUrl === normalizedRequestUrl;

            console.log('🔍 XHR比较URL:', {
              originalRequestUrl: requestUrl,
              originalInterceptUrl: item.url,
              normalizedRequestUrl: normalizedRequestUrl,
              normalizedInterceptUrl: normalizedInterceptUrl,
              match: match,
              requestUrlLength: normalizedRequestUrl.length,
              interceptUrlLength: normalizedInterceptUrl.length,
              requestUrlType: typeof normalizedRequestUrl,
              interceptUrlType: typeof normalizedInterceptUrl,
              charByCharMatch: match ? [] : normalizedRequestUrl.split('').map((char, i) => ({
                index: i,
                requestChar: char,
                interceptChar: normalizedInterceptUrl[i],
                match: char === normalizedInterceptUrl[i],
                requestCharCode: char.charCodeAt(0),
                interceptCharCode: normalizedInterceptUrl[i] ? normalizedInterceptUrl[i].charCodeAt(0) : 'undefined'
              })).filter(c => !c.match).slice(0, 5) // 只显示前5个不匹配的字符
            });

            // 完全匹配：规范化后的拦截地址和请求地址必须完全一样才拦截
            return match;
          });

        if (interceptedItem && interceptedItem.responseData) {
          console.log('🎯 拦截XHR响应:', xhr._interceptorData.url);

          // 通知content script有新请求（被拦截）
          window.postMessage({
            type: 'NEW_REQUEST',
            request: {
              ...xhr._interceptorData,
              responseData: interceptedItem.responseData,
              responseHeaders: responseHeaders,
              intercepted: true
            }
          }, '*');

          // 替换响应数据
          Object.defineProperty(xhr, 'responseText', {
            value: interceptedItem.responseData,
            writable: false
          });
          Object.defineProperty(xhr, 'response', {
            value: interceptedItem.responseData,
            writable: false
          });
        } else {
          // 通知content script有新请求和响应
          window.postMessage({
            type: 'NEW_REQUEST',
            request: {
              ...xhr._interceptorData,
              responseData: xhr.responseText || xhr.response,
              responseHeaders: responseHeaders
            }
          }, '*');
        }
      }

      if (originalOnReadyStateChange) {
        originalOnReadyStateChange.call(this);
      }
    };

    xhr.onload = function() {
      if (xhr._interceptorData && !responseSent) {
        responseSent = true;

        // 收集响应头
        const responseHeaders = {};
        try {
          const headerString = xhr.getAllResponseHeaders();
          if (headerString) {
            headerString.split('\r\n').forEach(line => {
              const parts = line.split(': ');
              if (parts.length === 2) {
                responseHeaders[parts[0]] = parts[1];
              }
            });
          }
        } catch (e) {
          console.warn('Failed to get response headers:', e);
        }

        // 检查是否有拦截的响应数据
        const normalizedRequestUrl = normalizeUrl(xhr._interceptorData.url);

        const interceptedItem = interceptConfig.enabled && !interceptConfig.batchDisableEnabled &&
          interceptConfig.intercepted.find(item => {
            if (!item.enabled) return false;

            // 规范化拦截URL并比较
            const normalizedInterceptUrl = normalizeUrl(item.url);
            return normalizedInterceptUrl === normalizedRequestUrl;
          });

        if (interceptedItem && interceptedItem.responseData) {
          console.log('🎯 拦截XHR响应:', xhr._interceptorData.url);

          // 通知content script有新请求（被拦截）
          window.postMessage({
            type: 'NEW_REQUEST',
            request: {
              ...xhr._interceptorData,
              responseData: interceptedItem.responseData,
              responseHeaders: responseHeaders,
              intercepted: true
            }
          }, '*');

          // 替换响应数据
          Object.defineProperty(xhr, 'responseText', {
            value: interceptedItem.responseData,
            writable: false
          });
          Object.defineProperty(xhr, 'response', {
            value: interceptedItem.responseData,
            writable: false
          });
        } else {
          // 通知content script有新请求和响应
          window.postMessage({
            type: 'NEW_REQUEST',
            request: {
              ...xhr._interceptorData,
              responseData: xhr.responseText || xhr.response,
              responseHeaders: responseHeaders
            }
          }, '*');
        }
      }

      if (originalOnLoad) {
        originalOnLoad.call(this);
      }
    };

    return originalSend.call(this, data);
  };

  // 简化的拦截逻辑：只匹配精确的URL
  // 用户修改参数后，就是要拦截新的接口，不再拦截旧接口

  // URL规范化函数 - 只规范化路径和参数，不改变协议和域名
  function normalizeUrl(url) {
    try {
      let urlObj;

      // 统一处理：都转换为绝对URL进行解析
      if (url.startsWith('/')) {
        urlObj = new URL(url, window.location.origin);
      } else if (!url.startsWith('http')) {
        urlObj = new URL(url, window.location.href);
      } else {
        urlObj = new URL(url);
      }

      // 只返回路径和参数部分，忽略协议和域名
      const pathname = urlObj.pathname;

      // 确保查询参数的顺序一致
      const params = new URLSearchParams(urlObj.search);
      const sortedParams = new URLSearchParams();

      // 按key排序添加参数
      Array.from(params.keys()).sort().forEach(key => {
        sortedParams.set(key, params.get(key));
      });

      const search = sortedParams.toString();
      return pathname + (search ? '?' + search : '');
    } catch (error) {
      console.warn('URL规范化失败:', error, 'URL:', url);
      return url; // 返回原始URL
    }
  }

  console.log('🔧 Request Interceptor 注入脚本已加载');
  console.log('🔧 调试函数已添加: debugInterceptor(), testIntercept()');

  // 立即显示当前状态
  setTimeout(() => {
    console.log('🔧 初始拦截配置:', interceptConfig);
  }, 1000);

  // 添加全局调试函数
  window.debugInterceptor = function() {
    console.log('🔧 拦截器调试信息:', {
      interceptConfig: interceptConfig,
      enabled: interceptConfig.enabled,
      interceptedCount: interceptConfig.intercepted ? interceptConfig.intercepted.length : 0,
      interceptedItems: interceptConfig.intercepted
    });

    if (interceptConfig.intercepted && interceptConfig.intercepted.length > 0) {
      console.log('🔧 拦截规则详情:');
      interceptConfig.intercepted.forEach((item, index) => {
        console.log(`  规则 ${index + 1}:`, {
          id: item.id,
          url: item.url,
          enabled: item.enabled,
          hasResponseData: !!item.responseData,
          responseDataLength: item.responseData ? item.responseData.length : 0
        });
      });
    }
  };

  // 添加测试拦截函数
  window.testIntercept = function(testUrl) {
    console.log('🔧 测试拦截匹配:', testUrl);

    if (!interceptConfig.enabled) {
      console.log('❌ 拦截器已禁用');
      return false;
    }

    const matchedItem = interceptConfig.intercepted.find(item => {
      if (!item.enabled) {
        console.log('❌ 规则已禁用:', item.url);
        return false;
      }

      const match = item.url === testUrl;
      console.log('🔍 URL匹配测试:', {
        ruleUrl: item.url,
        testUrl: testUrl,
        match: match,
        ruleUrlLength: item.url.length,
        testUrlLength: testUrl.length,
        ruleUrlType: typeof item.url,
        testUrlType: typeof testUrl,
        charByCharMatch: testUrl.split('').map((char, i) => ({
          index: i,
          testChar: char,
          ruleChar: item.url[i],
          match: char === item.url[i],
          testCharCode: char.charCodeAt(0),
          ruleCharCode: item.url[i] ? item.url[i].charCodeAt(0) : 'undefined'
        })).filter(c => !c.match).slice(0, 10) // 显示前10个不匹配的字符
      });

      return match;
    });

    console.log('🔍 匹配结果:', {
      found: !!matchedItem,
      hasResponseData: matchedItem ? !!matchedItem.responseData : false
    });

    return !!matchedItem;
  };

})();
